<template>
  <div class="training-recommendations">
    <el-card class="recommendations-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">培训建议</h1>
          <p class="page-subtitle">基于评价分析生成的个性化培训建议</p>
        </div>
        <div class="action-section">
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            创建建议
          </el-button>
          <el-button @click="refreshRecommendations" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="司机ID">
          <el-input v-model="filterForm.driverId" placeholder="请输入司机ID" clearable />
        </el-form-item>
        <el-form-item label="培训类型">
          <el-select v-model="filterForm.trainingType" placeholder="选择培训类型" clearable>
            <el-option label="服务技能" value="service_skill" />
            <el-option label="驾驶技能" value="driving_skill" />
            <el-option label="安全培训" value="safety_training" />
            <el-option label="沟通技巧" value="communication" />
            <el-option label="应急处理" value="emergency_handling" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="待实施" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 建议列表 -->
    <div class="recommendations-grid">
      <el-card 
        v-for="recommendation in recommendationsList" 
        :key="recommendation.id" 
        class="recommendation-card"
        :class="getStatusClass(recommendation.status)"
      >
        <div class="recommendation-header">
          <div class="recommendation-type">
            <el-tag :type="getTypeTagType(recommendation.training_type)" size="small">
              {{ getTypeLabel(recommendation.training_type) }}
            </el-tag>
            <el-tag :type="getStatusTagType(recommendation.status)" size="small">
              {{ getStatusLabel(recommendation.status) }}
            </el-tag>
          </div>
          <div class="recommendation-actions">
            <el-button type="primary" size="small" @click="viewDetail(recommendation)">
              查看详情
            </el-button>
            <el-button type="success" size="small" @click="editRecommendation(recommendation)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="updateStatus(recommendation)">
              更新状态
            </el-button>
          </div>
        </div>
        
        <div class="recommendation-content">
          <h3 class="recommendation-title">{{ recommendation.title }}</h3>
          <p class="recommendation-description">{{ recommendation.description }}</p>
          
          <div class="recommendation-details">
            <div class="detail-item">
              <span class="detail-label">司机ID:</span>
              <span class="detail-value">{{ recommendation.driver_id }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">培训时长:</span>
              <span class="detail-value">{{ recommendation.duration }} 小时</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">建议时间:</span>
              <span class="detail-value">{{ formatDate(recommendation.suggested_date) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">优先级:</span>
              <span class="detail-value">{{ getPriorityLabel(recommendation.priority) }}</span>
            </div>
          </div>
          
          <div class="recommendation-reasoning" v-if="recommendation.reasoning">
            <h4>建议依据</h4>
            <p>{{ recommendation.reasoning }}</p>
          </div>
          
          <div class="training-content" v-if="recommendation.training_content">
            <h4>培训内容</h4>
            <div class="content-list">
              <div v-for="(content, index) in recommendation.training_content" :key="index" class="content-item">
                <span class="content-number">{{ index + 1 }}</span>
                <span class="content-text">{{ content }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="pagination.total > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-if="recommendationsList.length === 0 && !loading" 
      description="暂无培训建议"
      :image-size="200"
    >
      <el-button type="primary" @click="showCreateDialog">创建建议</el-button>
    </el-empty>

    <!-- 创建/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑培训建议' : '创建培训建议'"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入培训建议标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入培训建议描述" 
          />
        </el-form-item>
        <el-form-item label="司机ID" prop="driver_id">
          <el-input v-model="form.driver_id" placeholder="请输入司机ID" />
        </el-form-item>
        <el-form-item label="培训类型" prop="training_type">
          <el-select v-model="form.training_type" placeholder="选择培训类型">
            <el-option label="服务技能" value="service_skill" />
            <el-option label="驾驶技能" value="driving_skill" />
            <el-option label="安全培训" value="safety_training" />
            <el-option label="沟通技巧" value="communication" />
            <el-option label="应急处理" value="emergency_handling" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训时长" prop="duration">
          <el-input-number v-model="form.duration" :min="1" :max="100" />
          <span class="unit">小时</span>
        </el-form-item>
        <el-form-item label="建议时间" prop="suggested_date">
          <el-date-picker
            v-model="form.suggested_date"
            type="date"
            placeholder="选择建议培训时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="建议依据" prop="reasoning">
          <el-input 
            v-model="form.reasoning" 
            type="textarea" 
            :rows="3"
            placeholder="请输入建议依据" 
          />
        </el-form-item>
        <el-form-item label="培训内容" prop="training_content">
          <el-input 
            v-model="form.training_content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入培训内容，每行一个要点" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 状态更新对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新状态" width="400px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status" placeholder="选择新状态">
            <el-option label="待实施" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="statusForm.notes" 
            type="textarea" 
            :rows="3"
            placeholder="请输入状态更新备注" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStatusUpdate" :loading="statusUpdateLoading">
            确认更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Plus } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const statusUpdateLoading = ref(false)
const recommendationsList = ref([])
const dialogVisible = ref(false)
const statusDialogVisible = ref(false)
const isEdit = ref(false)
const currentRecommendation = ref(null)

// 筛选表单
const filterForm = ref({
  driverId: '',
  trainingType: '',
  status: ''
})

// 分页
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
})

// 表单数据
const form = ref({
  title: '',
  description: '',
  driver_id: '',
  training_type: '',
  duration: 1,
  suggested_date: '',
  priority: '',
  reasoning: '',
  training_content: ''
})

// 状态表单
const statusForm = ref({
  status: '',
  notes: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  driver_id: [{ required: true, message: '请输入司机ID', trigger: 'blur' }],
  training_type: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
  duration: [{ required: true, message: '请输入培训时长', trigger: 'blur' }],
  suggested_date: [{ required: true, message: '请选择建议时间', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
}

const formRef = ref()

// 初始化页面
onMounted(() => {
  loadRecommendations()
})

// 加载建议列表
async function loadRecommendations() {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      page_size: pagination.value.pageSize
    }

    // 添加筛选条件
    if (filterForm.value.driverId) {
      params.driver_id = filterForm.value.driverId
    }
    if (filterForm.value.trainingType) {
      params.training_type = filterForm.value.trainingType
    }
    if (filterForm.value.status) {
      params.status = filterForm.value.status
    }

    const response = await evaluationAPI.getTrainingRecommendations(
      params.driver_id,
      params.page,
      params.page_size
    )
    
    if (response.data) {
      recommendationsList.value = response.data.data || []
      pagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('加载培训建议失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选
function applyFilter() {
  pagination.value.page = 1
  loadRecommendations()
}

// 重置筛选
function resetFilter() {
  filterForm.value = {
    driverId: '',
    trainingType: '',
    status: ''
  }
  pagination.value.page = 1
  loadRecommendations()
}

// 刷新建议
async function refreshRecommendations() {
  loading.value = true
  await loadRecommendations()
  ElMessage.success('数据已刷新')
  loading.value = false
}

// 显示创建对话框
function showCreateDialog() {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑建议
function editRecommendation(recommendation) {
  isEdit.value = true
  currentRecommendation.value = recommendation
  form.value = {
    title: recommendation.title,
    description: recommendation.description,
    driver_id: recommendation.driver_id,
    training_type: recommendation.training_type,
    duration: recommendation.duration,
    suggested_date: recommendation.suggested_date,
    priority: recommendation.priority,
    reasoning: recommendation.reasoning,
    training_content: Array.isArray(recommendation.training_content) 
      ? recommendation.training_content.join('\n')
      : recommendation.training_content
  }
  dialogVisible.value = true
}

// 重置表单
function resetForm() {
  form.value = {
    title: '',
    description: '',
    driver_id: '',
    training_type: '',
    duration: 1,
    suggested_date: '',
    priority: '',
    reasoning: '',
    training_content: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = {
      ...form.value,
      training_content: form.value.training_content.split('\n').filter(item => item.trim())
    }
    
    let response
    if (isEdit.value) {
      response = await evaluationAPI.updateTrainingRecommendation(currentRecommendation.value.id, submitData)
    } else {
      response = await evaluationAPI.createTrainingRecommendation(submitData)
    }
    
    if (response.data) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      await loadRecommendations()
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
function viewDetail(recommendation) {
  router.push(`/evaluation/training/detail/${recommendation.id}`)
}

// 更新状态
function updateStatus(recommendation) {
  currentRecommendation.value = recommendation
  statusForm.value = {
    status: recommendation.status,
    notes: ''
  }
  statusDialogVisible.value = true
}

// 确认状态更新
async function confirmStatusUpdate() {
  statusUpdateLoading.value = true
  try {
    // 这里可以调用API更新状态
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    await loadRecommendations()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  } finally {
    statusUpdateLoading.value = false
  }
}

// 获取状态样式类
function getStatusClass(status) {
  const classes = {
    pending: 'status-pending',
    in_progress: 'status-progress',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return classes[status] || ''
}

// 获取类型标签类型
function getTypeTagType(type) {
  const types = {
    service_skill: 'primary',
    driving_skill: 'success',
    safety_training: 'warning',
    communication: 'info',
    emergency_handling: 'danger'
  }
  return types[type] || 'default'
}

// 获取状态标签类型
function getStatusTagType(status) {
  const types = {
    pending: 'info',
    in_progress: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'default'
}

// 获取类型标签
function getTypeLabel(type) {
  const labels = {
    service_skill: '服务技能',
    driving_skill: '驾驶技能',
    safety_training: '安全培训',
    communication: '沟通技巧',
    emergency_handling: '应急处理'
  }
  return labels[type] || type
}

// 获取状态标签
function getStatusLabel(status) {
  const labels = {
    pending: '待实施',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return labels[status] || status
}

// 获取优先级标签
function getPriorityLabel(priority) {
  const labels = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return labels[priority] || priority
}

// 分页处理
function handleSizeChange(size) {
  pagination.value.pageSize = size
  pagination.value.page = 1
  loadRecommendations()
}

function handleCurrentChange(page) {
  pagination.value.page = page
  loadRecommendations()
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.training-recommendations {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.recommendations-header {
  margin-bottom: 20px;
  border-radius: 12px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
  border-radius: 12px;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.recommendation-card {
  border-radius: 12px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.recommendation-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.recommendation-card.status-pending {
  border-left: 4px solid #909399;
}

.recommendation-card.status-progress {
  border-left: 4px solid #e6a23c;
}

.recommendation-card.status-completed {
  border-left: 4px solid #67c23a;
}

.recommendation-card.status-cancelled {
  border-left: 4px solid #f56c6c;
}

.recommendation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.recommendation-type {
  display: flex;
  gap: 8px;
}

.recommendation-actions {
  display: flex;
  gap: 8px;
}

.recommendation-content {
  margin-top: 16px;
}

.recommendation-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.recommendation-description {
  margin: 0 0 16px 0;
  color: #606266;
  line-height: 1.6;
}

.recommendation-details {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-weight: 500;
  color: #606266;
}

.detail-value {
  color: #303133;
}

.recommendation-reasoning {
  margin-bottom: 16px;
}

.recommendation-reasoning h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.recommendation-reasoning p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.training-content {
  margin-bottom: 16px;
}

.training-content h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.content-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.content-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.content-text {
  color: #606266;
  line-height: 1.5;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.unit {
  margin-left: 8px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .recommendations-grid {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .action-section {
    justify-content: center;
  }
  
  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .recommendation-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .recommendation-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 